package com.jzo2o.foundations.handler;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.service.HomeService;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * springCache缓存同步任务
 *
 * @author itcast
 * @create 2023/8/15 18:14
 **/
@Slf4j
@Component
public class SpringCacheSyncHandler {

    @Resource
    private IRegionService regionService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private HomeService homeService;
    /**
     * 已启用区域缓存更新，（包括区域缓存，区域下的服务缓存）
     * 每日凌晨1点执行
     */
    @XxlJob(value = "activeRegionCacheSync")
    public void activeRegionCacheSync() {
        log.info(">>>>>>>>开始进行缓存同步，更新已启用区域");
        //1.清理已开通地区缓存
        String key = RedisConstants.CacheName.JZ_CACHE + "::ACTIVE_REGIONS";
        redisTemplate.delete(key);
        //通过查询开通区域列表进行缓存
        List<RegionSimpleResDTO> regionSimpleResDTOS = regionService.queryActiveRegionList();
        for (RegionSimpleResDTO regionSimpleResDTO : regionSimpleResDTOS) {
            Long regionId = regionSimpleResDTO.getId();
            //删除该区域下的首页服务列表
            String serve_key = RedisConstants.CacheName.SERVE_ICON + "::" + regionId;
            redisTemplate.delete(serve_key);

            //删除该区域下的首页服务类型列表
            String serve_type_key = RedisConstants.CacheName.SERVE_TYPE + "::" + regionId;
            redisTemplate.delete(serve_type_key);

            //删除该区域下的首页热门服务
            String serve_hot_key = RedisConstants.CacheName.HOT_SERVE + "::" + regionId;
            redisTemplate.delete(serve_hot_key);

            //更新已开通区域的服务缓存
            homeService.queryServeIconCategoryByRegionIdCache(regionId);
            //更新已开通区域的服务缓存
            homeService.getServeTypeListByRegionId(regionId);
            //更新已开通区域的热门
            homeService.getHotServeList(regionId);
        }


        //2.刷新开通区域缓存缓存
        regionService.queryActiveRegionListCache();
        log.info(">>>>>>>>更新已启用区域完成");
    }

}